package com.group02.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group02.community.entity.user.SysRole;
import com.group02.community.entity.user.SysRoleMenu;
import com.group02.community.entity.vo.queryVO.RoleQueryVO;
import com.group02.community.mapper.RoleMapper;
import com.group02.community.mapper.RoleMenuMapper;
import com.group02.community.service.IRoleMenuService;
import com.group02.community.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, SysRole> implements IRoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    IRoleMenuService roleMenuService;


    @Override
    public IPage<SysRole> getRolePage(Long current, Long size , RoleQueryVO rq) {
        return roleMapper.selectAllRole(new Page<SysRole>(current,size),rq);
    }

    @Override
    public SysRole getRoleById(Long id) {
        return roleMapper.selectOne(new QueryWrapper<SysRole>().lambda().eq(SysRole::getRoleId,id));
    }

    @Override
    @Transactional
    public String addAllRoleMsg(SysRole role) {
        SysRole sysRole = roleMapper.selectOne(new QueryWrapper<SysRole>().lambda().eq(SysRole::getRoleName, role.getRoleName()));
        if (sysRole==null){
            roleMapper.insert(role);
            SysRole newRole = roleMapper.selectOne(new QueryWrapper<SysRole>().lambda().eq(SysRole::getRoleName, role.getRoleName()));
            long roleId = newRole.getRoleId();
            List<Long> menuIds = role.getMenuIds();
            ArrayList<SysRoleMenu> sysRolesMenu = new ArrayList<>();
            for (int i = 0; i < menuIds.size(); i++) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu(roleId, menuIds.get(i));
                sysRolesMenu.add(sysRoleMenu);
            }
            roleMenuService.saveBatch(sysRolesMenu);
            return "添加成功";
        }

        return "角色名重复";
    }

    @Override
    @Transactional
    public String updateAllRoleMsg(SysRole role) {
        roleMapper.updateById(role);
        long roleId = role.getRoleId();
        roleMenuService.deleteByAllRoleId(roleId);
        List<Long> menuIds = role.getMenuIds();
        ArrayList<SysRoleMenu> sysRolesMenu = new ArrayList<>();
        for (int i = 0; i < menuIds.size(); i++) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu(roleId, menuIds.get(i));
            sysRolesMenu.add(sysRoleMenu);
        }
        roleMenuService.saveBatch(sysRolesMenu);
        return "修改成功";


    }
}
